package main

import (
	"IMServices/NetIO/Define"
	"IMServices/NetIO/Packet"
	"net"
)
import (
	"bytes"
	"encoding/binary"
	"encoding/json"
)

func messageRequestToBytes(msg Packet.MessageRequest, c Define.LoginDefine) ([]byte, error) {
	// 将 MsgBody 序列化为 JSON 字符串
	loginByte, _ := loginDefineToBytes(c)
	var err error
	//jsonBytes, err := json.Marshal(msg.MsgBody)
	//if err != nil {
	//	return nil, err
	//}
	i := len(loginByte)
	msg.MsgHeader.PacketLength = int32(i) + 20
	// 构造消息头部字节流
	headerBuf := new(bytes.Buffer)
	err = binary.Write(headerBuf, binary.BigEndian, msg.MsgHeader.PacketLength)
	if err != nil {
		return nil, err
	}
	err = binary.Write(headerBuf, binary.BigEndian, msg.MsgHeader.Method)
	if err != nil {
		return nil, err
	}
	err = binary.Write(headerBuf, binary.BigEndian, msg.MsgHeader.HeaderLength)
	if err != nil {
		return nil, err
	}
	err = binary.Write(headerBuf, binary.BigEndian, msg.MsgHeader.OrderIndex)
	if err != nil {
		return nil, err
	}
	err = binary.Write(headerBuf, binary.BigEndian, msg.MsgHeader.Status)
	if err != nil {
		return nil, err
	}
	err = binary.Write(headerBuf, binary.BigEndian, msg.MsgHeader.EncodeType)
	if err != nil {
		return nil, err
	}
	err = binary.Write(headerBuf, binary.BigEndian, msg.MsgHeader.Extend1)
	if err != nil {
		return nil, err
	}
	err = binary.Write(headerBuf, binary.BigEndian, msg.MsgHeader.Extend2)
	if err != nil {
		return nil, err
	}

	// 组合消息头部和消息体字节流
	buf := bytes.NewBuffer(headerBuf.Bytes())
	buf.Write(loginByte)

	return buf.Bytes(), nil
}

func loginDefineToBytes(login Define.LoginDefine) ([]byte, error) {
	// 序列化 LoginDefine 结构体为 JSON 字符串
	jsonBytes, err := json.Marshal(login)
	if err != nil {
		return nil, err
	}

	return jsonBytes, nil
}

func main() {
	tcp, err := net.Dial("tcp", "localhost:33781")
	if err != nil {
		return
	}
	login := Define.LoginDefine{Name: "niubi", ServerId: "123", Password: "123", Ip: "127.0.0.1", PlatForm: "1", LoginFlag: "1"}

	pack := Packet.MessageRequest{}
	pack.MsgHeader = Packet.Header{PacketLength: 1, Method: 1, HeaderLength: 20, OrderIndex: 1, Status: 1, EncodeType: 1, Extend1: 1, Extend2: 1}

	toBytes, _ := messageRequestToBytes(pack, login)
	_, err = tcp.Write(toBytes)
	if err != nil {
		return
	}
}
